//
//  DHUserInfoController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/12.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHUserInfoController.h"
#import "DHAreaList.h"
#import "DHAreaModel.h"
#import <CZPickerView.h>
#import "DHUserInfoHeaderView.h"
@interface DHUserInfoController ()<CZPickerViewDataSource,CZPickerViewDelegate,UITableViewDelegate,
                                    PGDatePickerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *bankNumTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *subBankTxtFiled;
@property (weak, nonatomic) IBOutlet UITextField *nameTxtFiled;
@property(nonatomic ,strong)DHNavbarView *navbar;
@property (weak, nonatomic) IBOutlet UIButton *provinceButton;
@property (weak, nonatomic) IBOutlet UIButton *birthdayButton;
@property(nonatomic ,strong)DHAreaList *areaList;
@property (weak, nonatomic) IBOutlet UILabel *addressInfoLabel;
@property(nonatomic ,strong)DHAreaModel *province; // 记录选择选择的地区
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property(nonatomic ,strong)NSString *province_id;
@property(nonatomic ,strong)NSString *city_id;
@property(nonatomic ,strong)NSString *area_id;
@property (weak, nonatomic) IBOutlet UIImageView *tipImgView;
@property (weak, nonatomic) IBOutlet UIImageView *tipImgView1;
@property (weak, nonatomic) IBOutlet UIImageView *tipImgView2;

@property (weak, nonatomic) IBOutlet UIButton *cityButton; // 城市按钮
@property (weak, nonatomic) IBOutlet UIButton *regionButton; // 区按钮
@property (weak, nonatomic) IBOutlet UIButton *maleButton; // 男 按钮
@property (weak, nonatomic) IBOutlet UIButton *privacyButton; // 保密 按钮
@property (weak, nonatomic) IBOutlet UIButton *femaleButton; // 女 按钮

@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property(nonatomic ,strong)UIButton *btnCurrentGender; // 记录性别选择按钮 默认 男
@property (weak, nonatomic) IBOutlet UIButton *btnSelectedBank; // 选择银行按钮
@property(nonatomic ,strong)NSArray *bankList; // 银行数组

@property(nonatomic ,assign,getter=isBankDatas)BOOL bankDatas; // 用来判断数据

@property(nonatomic ,strong)CZPickerView *pickerView;

//@property(nonatomic ,strong)NSString *state; // 认证状态

@property(nonatomic ,strong)DHAuthodDatasModel *model;
@end

@implementation DHUserInfoController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupUI];
}
- (void)setModel:(DHAuthodDatasModel *)model
{
    _model = model;
    
    if (model.state.integerValue == 0 || model.state.integerValue == 1)
    {
        self.cityButton.userInteractionEnabled = false;
        self.provinceButton.userInteractionEnabled = false;
        self.regionButton.userInteractionEnabled = false;
        self.maleButton.userInteractionEnabled = false;
        self.femaleButton.userInteractionEnabled = false;
        self.privacyButton.userInteractionEnabled =false;
        self.btnSelectedBank.userInteractionEnabled = false;
        self.bankNumTextFiled.userInteractionEnabled = false;
        self.subBankTxtFiled.userInteractionEnabled = false;
        self.birthdayButton.userInteractionEnabled = false;
        self.nameTxtFiled.userInteractionEnabled = false;
        
        self.nameTxtFiled.text = model.member_auth_info.name;
        
        switch (model.member_auth_info.sex.intValue) {
            case 1:
                self.maleButton.selected = YES;
                self.femaleButton.selected = NO;
                self.privacyButton.selected = NO;
                break;
            case 2:
                self.maleButton.selected = NO;
                self.femaleButton.selected = YES;
                self.privacyButton.selected = NO;
                break;
            default:
                self.maleButton.selected = NO;
                self.femaleButton.selected = NO;
                self.privacyButton.selected = YES;
                break;
        }
        [self.birthdayButton setTitle:model.member_auth_info.birthday forState:UIControlStateNormal];
        [self.btnSelectedBank setTitle:model.member_auth_info.bank_name forState:UIControlStateNormal];
        self.subBankTxtFiled.text = model.member_auth_info.bank_address;
        self.bankNumTextFiled.text = model.member_auth_info.crad_id;
        self.phoneLabel.text = model.member_auth_info.mobile;
        self.tipImgView.hidden = YES;
        self.tipImgView1.hidden = YES;
        self.tipImgView2.hidden = YES;
        self.cityButton.hidden = YES;
        self.provinceButton.hidden = YES;
        self.regionButton.hidden = YES;
        
        self.addressInfoLabel.hidden = false;
        self.addressInfoLabel.text = model.member_auth_info.area_info;
        
        self.saveButton.userInteractionEnabled = false;
    }
    
    [self.tableView reloadData];
}
#pragma mark: - 生日按钮监听
- (IBAction)birthdayButtonClick:(UIButton *)sender
{
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.datePickerMode = PGDatePickerModeDate;
    [self presentViewController:datePickManager animated:false completion:nil];
    
    //设置取消按钮的字
    datePickManager.cancelButtonText = @"取消";
    //设置确定按钮的字
    datePickManager.confirmButtonText = @"确定";


}
#pragma mark: - PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents
{
    NSString *birthday = [NSString stringWithFormat:@"%zd-%02zd-%zd",dateComponents.year,dateComponents.month,dateComponents.day];
    
    [self.birthdayButton setTitle:birthday forState:UIControlStateNormal];
    
}

- (DHAreaList *)areaList{
    if (!_areaList)
    {
        _areaList = [[DHAreaList alloc] init];
        [self loadAreaData];
    }
    return _areaList;
}
#pragma mark: - 实例化
+ (instancetype)userInfo
{
    UIStoryboard * story = [UIStoryboard storyboardWithName:@"DHUserInfoController" bundle:nil];
    
    DHUserInfoController *userInfoVC = [story instantiateViewControllerWithIdentifier:@"userInfo"];
    
    return userInfoVC;
}

#pragma mark: - 选择银行 的按钮监听
- (IBAction)selectBankButtonClick:(UIButton *)sender
{
    self.bankDatas = YES;
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"请选择银行"
                                              cancelButtonTitle:@"取消"
                                             confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView show];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
   // self.tableView.delegate = self;
    [self setupUI];
    [self loadAreaData];
    [self loadBankList];
    [self loadUserInfoData];
}
#pragma mark: - 加载用户信息
- (void)loadUserInfoData
{
    NSMutableDictionary *paramM = [NSMutableDictionary dictionary];
    
    paramM[@"key"] = [DHNetworkManager.shareManager.userAccount key];
    
    [DHNetworkManager.shareManager postMemberAuthodWithParams:paramM.copy
    finished:^(BOOL isSuccess, DHAuthodDatasModel *datasModel, NSString *error)
    {
        if (!isSuccess)
        {
            [SVProgressHUD showErrorWithStatus:@"请检查网络"];
            return ;
        }
        if (error) {
            [SVProgressHUD showErrorWithStatus:error];
            return ;
        }
        
        self.model = datasModel;
      
    }];
}

#pragma mark: - 性别选择按钮监听
- (void)selectedGenderClick:(UIButton *)sender
{
    self.btnCurrentGender.selected = NO;
    sender.selected = YES;
    self.btnCurrentGender = sender;
}
#pragma mark: - 加载银行数据
- (void)loadBankList
{
    NSString *url = @"http://jpjd.cnaite.cn/mobile/index.php?act=index&op=getBank";
    
    [DHNetworkManager.shareManager requestWithMethod:MethodGet
                                           UrlString:url
                                    params:nil completion:^(id json, BOOL isSuccess)
     {
         if (!isSuccess)
         {
             [SVProgressHUD showErrorWithStatus:@"请检查网络"];
             return ;
         }
         self.bankList = [NSArray yy_modelArrayWithClass:[DHBankModel class] json:json[@"datas"][@"list"]];
         
         [self.pickerView reloadData];
     }];
}
#pragma mark: - 加载地区数据
- (void)loadAreaData
{
    NSString *url = @"http://jpjd.cnaite.cn/mobile/index.php?act=index&op=getArea";
    
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"area_id"] = self.province.area_id;
    
    [DHNetworkManager.shareManager requestWithMethod:MethodGet
                                           UrlString:url
                                              params:params.copy
                                          completion:^(id json, BOOL isSuccess)
     {
         if (!isSuccess)
         {
             [SVProgressHUD showErrorWithStatus:@"请检查网络"];
             return ;
         }
         
         self.areaList = [DHAreaList yy_modelWithJSON:json[@"datas"]];
         
         [self.pickerView reloadData];
     }];

}
#pragma mark: - UITableViewDelegate
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 1)
    {
       return [self creatHeaderViewWithTitle:@"个人信息" isHiddenState:NO];
    }else if (section == 2){
       return [self creatHeaderViewWithTitle:@"银行信息" isHiddenState:YES];

    }
    
    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ((section == 1) || (section == 2))
    {
        return 44;
    }
    return 0;
}

#pragma mark: - 创建headerView
- (UIView *)creatHeaderViewWithTitle:(NSString *)title isHiddenState:(BOOL)isHidden
{
    NSString *state;
    switch (self.model.state.intValue) {
        case -1:
            state = @"未认证";
            break;
        case 0:
            state = @"待处理";
            break;
        case 1:
            state = @"已通过";
            break;
        case 2:
            state = @"未通过";
        default:
            break;
    }
    DHUserInfoHeaderView *header = [DHUserInfoHeaderView headerViewWithTitle:title isHaveAuthod:isHidden state:state];
    return header;
}

// 设置界面
- (void)setupUI{
   // self.view.backgroundColor = UIColor.whiteColor;
   // self.navigationController.navigationBar.hidden = true;
  //  __weak typeof(self) WeakSelf = self;
//    [self.view addSubview:self.navbar];
    self.navigationController.navigationBar.hidden = false;
//    self.navbar.popButtonClickBlock = ^{
//        [WeakSelf.navigationController popViewControllerAnimated:true];
//    };
    self.title = @"精品酒店网";
    self.navigationController.navigationBar.tintColor = UIColor.whiteColor;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:UIColor.whiteColor};
    //self.navigationController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] ini]
    // 设置性别按钮 图像
    UIImage *selectedImg = [UIImage createNewImage:[UIImage imageNamed:@"gouxuan"] newSize:CGSizeMake(27, 27)];
    UIImage *normalImg = [UIImage createNewImage:[UIImage imageNamed:@"圆角矩形 1(2)"] newSize:CGSizeMake(27, 27)];
    
    [self.maleButton setImage:normalImg forState:UIControlStateNormal];
    [self.maleButton setImage:selectedImg forState:UIControlStateSelected];
    [self.maleButton addTarget:self action:@selector(selectedGenderClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.femaleButton setImage:normalImg forState:UIControlStateNormal];
    [self.femaleButton setImage:selectedImg forState:UIControlStateSelected];
    [self.femaleButton addTarget:self action:@selector(selectedGenderClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.privacyButton setImage:normalImg forState:UIControlStateNormal];
    [self.privacyButton setImage:selectedImg forState:UIControlStateSelected];
    [self.privacyButton addTarget:self action:@selector(selectedGenderClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 默认选择男
    [self selectedGenderClick:self.maleButton];
    
}
#pragma mark: - 省份按钮点击
- (IBAction)provinceButtonClick:(UIButton *)sender
{
    self.bankDatas = false;
    
    self.province = nil;
    //NSLog(@"%@",sender.currentTitle);
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"省份"
                                                   cancelButtonTitle:@"取消"
                                                  confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView show];
    
}
#pragma mark: - 城市按钮点击
- (IBAction)cityButtonClick:(UIButton *)sender
{
    self.bankDatas = false;
    
    if (!self.province) {
        [SVProgressHUD showErrorWithStatus:@"请选择省份"];
        return;
    }
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"城市"
                                              cancelButtonTitle:@"取消"
                                             confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;

   // NSLog(@"%@",self.areaList.list.firstObject[@"area_name"]);
    [self.pickerView show];
}
#pragma mark: - 地区按钮点击
- (IBAction)regionButtonClick:(UIButton *)sender
{
    self.bankDatas = false;
    
    if (!self.province) {
        [SVProgressHUD showErrorWithStatus:@"请选择城市"];
        return;
    }
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"地区"
                                              cancelButtonTitle:@"取消"
                                             confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView show];

}
#pragma mark: - CZPickerViewDataSource,CZPickerViewDelegate
- (NSInteger)numberOfRowsInPickerView:(CZPickerView *)pickerView
{
    return self.isBankDatas ? self.bankList.count : self.areaList.list.count;
}
- (NSAttributedString *)czpickerView:(CZPickerView *)pickerView
               attributedTitleForRow:(NSInteger)row
{
    NSString *title = self.isBankDatas ? [self.bankList[row] name] : [self.areaList.list[row] area_name];
    return [[NSAttributedString alloc] initWithString:title];
}
- (void)czpickerView:(CZPickerView *)pickerView didConfirmWithItemAtRow:(NSInteger)row
{
    
    if (self.isBankDatas)
    {
        [self.btnSelectedBank setTitle:[self.bankList[row] name] forState:UIControlStateNormal];
        return;
    }
    [self setButtonTitleWithDeep:self.areaList.deep.integerValue selectedRow:row];
    self.province = self.areaList.list[row];
    self.areaList = nil;

}

- (void)setButtonTitleWithDeep:(NSInteger)deep
                   selectedRow:(NSInteger)row
{
    
    switch (deep) {
        case 1:
            [self.provinceButton setTitle:[self.areaList.list[row] area_name] forState:UIControlStateNormal];
            self.province_id = [self.areaList.list[row] area_id];
            break;
        case 2:
            [self.cityButton setTitle:[self.areaList.list[row] area_name] forState:UIControlStateNormal];
            self.city_id = [self.areaList.list[row] area_id];

            break;
        default:
            [self.regionButton setTitle:[self.areaList.list[row] area_name] forState:UIControlStateNormal];
            self.area_id = [self.areaList.list[row] area_id];
            self.province = nil;
            [self loadAreaData];
            break;
    }
}
- (IBAction)saveButtonClick:(UIButton *)sender
{

    if (!self.nameTxtFiled.hasText)
    {[SVProgressHUD showErrorWithStatus:@"请输入姓名"];return;}
    
    
    if ([self.provinceButton.currentTitle isEqualToString:@"省份"] ||
        [self.cityButton.currentTitle isEqualToString:@"城市"] ||
        [self.regionButton.currentTitle isEqualToString:@"区"])
    {[SVProgressHUD showErrorWithStatus:@"请选择所在城市"];return;}
    
    if ([self.birthdayButton.currentTitle isEqualToString:@"请选择生日"]) {[SVProgressHUD showErrorWithStatus:self.birthdayButton.currentTitle];return;}
    
    if([self.btnSelectedBank.currentTitle isEqualToString:@"请选择银行"])
    {[SVProgressHUD showErrorWithStatus:@"请选择银行"];return;}
    
    if (!self.subBankTxtFiled.hasText)
    {[SVProgressHUD showErrorWithStatus:@"请输入开户支行"];return;}
    
    if (!self.bankNumTextFiled.hasText)
    {[SVProgressHUD showErrorWithStatus:@"请输入银行卡号"];return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    params[@"name"] = self.nameTxtFiled.text;
    params[@"sex"] = self.btnCurrentGender.currentTitle;
    params[@"birthday"] = self.birthdayButton.currentTitle;
    params[@"province_id"] = self.province_id;
    params[@"city_id"] = self.city_id;
    params[@"area_id"] = self.area_id;
    params[@"area_info"] = [NSString stringWithFormat:@"%@%@%@",self.provinceButton.currentTitle,self.cityButton.currentTitle,self.regionButton.currentTitle];
    params[@"bank_name"] = self.btnSelectedBank.currentTitle;
    params[@"bank_address"] = self.subBankTxtFiled.text;
    params[@"crad_id"] = self.bankNumTextFiled.text;
    
    //NSLog(@"%@",params);
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"DHConfirmIDController" bundle:nil];
    DHConfirmIDController *confirmVC = [sb instantiateViewControllerWithIdentifier:@"ConfirmIDControllerID"];
    confirmVC.postParams = params;
    [self.navigationController pushViewController:confirmVC animated:true];
}

@end
